<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">

  <title>主页-XX管理系统</title>

  <!-- Favicons -->
  <link href="assets/img/favicon.png" rel="icon">

  <!-- Vendor CSS Files -->
  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">

  <!-- Template Main CSS File -->
  <link href="assets/css/style.css" rel="stylesheet">
  <style>
  .profile-info {
      text-align: center;
      margin-bottom: 20px;
    }

  .profile-info img {
      width: 150px;
      height: 150px;
      border-radius: 50%;
    }

  .nav-tabs.nav-link {
      border: none;
    }

  .nav-tabs.nav-link.active {
      border-bottom: 2px solid #007bff;
    }
  </style>
</head>

<body>

  <!-- ======= Header ======= -->
  <header id="header" class="header fixed-top d-flex align-items-center">

    <div class="d-flex align-items-center justify-content-between">
      <a href="index.html" class="logo d-flex align-items-center">
        <img src="assets/img/logo.png" alt="">
        <span class="d-none d-lg-block">XX管理系统</span>
      </a>
      <i class="bi bi-list toggle-sidebar-btn"></i>
    </div><!-- End Logo -->

    <nav class="header-nav ms-auto">
      <ul class="d-flex align-items-center">
        <li class="nav-item dropdown pe-3">

          <a class="nav-link nav-profile d-flex align-items-center pe-0" href="#" data-bs-toggle="dropdown">
            <img src="assets/img/profile-img.jpg" alt="Profile" class="rounded-circle">
            <span class="d-none d-md-block dropdown-toggle ps-2">用户名</span>
          </a><!-- End Profile Iamge Icon -->

          <ul class="dropdown-menu dropdown-menu-end dropdown-menu-arrow profile">
            <li class="dropdown-header">
              <h6>部门名</h6>
              <span>角色名</span>
            </li>
            <li>
              <hr class="dropdown-divider">
            </li>
            <li>
              <a class="dropdown-item d-flex align-items-center" href="index.html">
                <i class="bi bi-gear"></i>
                <span>个人信息</span>
              </a>
            </li>
            <li>
              <hr class="dropdown-divider">
            </li>
            <li>
              <a class="dropdown-item d-flex align-items-center" href="#">
                <i class="bi bi-box-arrow-right"></i>
                <span>注销登录</span>
              </a>
            </li>

          </ul><!-- End Profile Dropdown Items -->
        </li><!-- End Profile Nav -->

      </ul>
    </nav><!-- End Icons Navigation -->

  </header><!-- End Header -->

  <!-- ======= Sidebar ======= -->
  <aside id="sidebar" class="sidebar">

    <ul class="sidebar-nav" id="sidebar-nav">

      <li class="nav-item">
        <a class="nav-link " href="index.html">
          <i class="bi bi-grid"></i>
          <span>个人主页</span>
        </a>
      </li><!-- End Dashboard Nav -->

      <li class="nav-item">
        <a class="nav-link collapsed" data-bs-target="#components-nav" data-bs-toggle="collapse" href="#">
          <i class="bi bi-menu-button-wide"></i><span>系统管理</span><i class="bi bi-chevron-down ms-auto"></i>
        </a>
        <ul id="components-nav" class="nav-content collapse " data-bs-parent="#sidebar-nav">
          <li>
            <a href="system-user.html">
              <i class="bi bi-circle"></i><span>用户管理</span>
            </a>
          </li>
          <li>
            <a href="system-dept.html">
              <i class="bi bi-circle"></i><span>部门管理</span>
            </a>
          </li>
          <li>
            <a href="system-role.html">
              <i class="bi bi-circle"></i><span>角色管理</span>
            </a>
          </li>
        </ul>
      </li><!-- End Components Nav -->

      <li class="nav-item">
        <a class="nav-link collapsed" href="blank.html">
          <i class="bi bi-file-earmark"></i>
          <span>空白模板页</span>
        </a>
      </li><!-- End Blank Page Nav -->

    </ul>

  </aside><!-- End Sidebar-->

  <main id="main" class="main">
    <div class="pagetitle">
      <nav>
        <ol class="breadcrumb">
          <li class="breadcrumb-item active">主页</li>
        </ol>
      </nav>
    </div><!-- End Page Title -->

    <section class="section">
      <div class="container">
        <div class="row">
          <div class="col-md-4">
            <div class="profile-info">
              <img id="userAvatar" src="assets/img/profile-img.jpg" alt="Profile">
              <h4 id="username">用户名</h4>
              <p id="department">部门名</p>
              <p id="role">角色名</p>
            </div>
          </div>
          <div class="col-md-8">
            <div class="profile-content">
              <ul class="nav nav-tabs">
                <li class="nav-item">
                  <a class="nav-link active" href="#overview" data-bs-toggle="tab">个人概述</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="#editUser" data-bs-toggle="tab">编辑信息</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="#changePwdForm" data-bs-toggle="tab">修改密码</a>
                </li>
              </ul>
              <div class="tab-content">
                <div class="tab-pane active" id="overview">
                  <h3>个人资料</h3>
                  <div id="userInfo">
                    <p><strong>姓 名:</strong> <span id="userName">张三</span></p>
                    <p><strong>所属部门:</strong> <span id="department1">部门名</span></p>
                    <p><strong>系统角色:</strong> <span id="role1">角色名</span></p>
                    <p><strong>联系方式:</strong> <span id="userPhone">1234567890</span></p>
                    <p><strong>邮箱地址:</strong> <span id="userEmail">example@example.com</span></p>
                  </div>
                </div>
                <div class="tab-pane" id="editUser">
                  <form id="editUserForm" class="needs-validation" novalidate>
                  <h3>编辑信息</h3>
                  <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="px-5">
                            <div id="editUserAlert"></div>
                            <div class="row mb-3">
                                <label for="fileInput" class="col-sm-2 col-form-label d-flex justify-content-end">头像</label>
                                <div class="col-sm-10">
                                    <input type="hidden" class="form-control" name="avatar" />
                                    <input type="file" id="avatarFileInput" style="display: none" accept=".jpg,.jpeg,.png" />
                                    <img id="userAvatarImg" src="assets/img/user.png" alt="用户头像" height="120px" />
                                    <div class="pt-2">
                                        <a id="uploadAvatarButton" class="btn btn-primary btn-sm" title="上传新的头像">
                                            <i class="bi bi-upload"></i>
                                        </a>
                                        <a id="removeAvatarButton" class="btn btn-danger btn-sm" title="删除用户头像">
                                            <i class="bi bi-trash"></i>
                                        </a>
                                    </div>
                                    <div id="uploadAvatarAlert" class="mt-3"></div>
                                </div>
                            </div>
                            <div class="row mb-3">
                                <label for="name" class="col-sm-2 col-form-label d-flex justify-content-end">姓名</label>
                                <div class="col-sm-10">
                                    <input type="text" class="form-control" id="name" name="name" required />
                                </div>
                            </div>
                            <div class="row mb-3">
                                <label for="phone" class="col-sm-2 col-form-label d-flex justify-content-end">手机号码</label>
                                <div class="col-sm-10">
                                    <input type="text" class="form-control" id="phone" name="phone" />
                                </div>
                            </div>
                            <div class="row mb-3">
                                <label for="email" class="col-sm-2 col-form-label d-flex justify-content-end">邮箱</label>
                                <div class="col-sm-10">
                                    <input type="email" class="form-control" id="email" name="email" />
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary">提交</button>
                    </div>
                  </div>                                                                      
                </div>
              </form>  
                <div class="tab-pane" id="changePwdForm">
                    <h3>修改密码</h3>
                    <form id="changePwdForm">
                        <div class="mb-3">
                          <label for="oldPassword" class="form-label">旧密码</label>
                          <input type="password" class="form-control" id="oldPassword" required>
                        </div>
                        <div class="mb-3">
                            <label for="newPassword" class="form-label">新密码</label>
                            <input type="password" class="form-control" id="newPassword" required>
                        </div>
                        <div class="mb-3">
                            <label for="confirmPassword" class="form-label">确认密码</label>
                            <input type="password" class="form-control" id="confirmPassword" required>
                        </div>
                        <button type="submit" class="btn btn-primary">修改密码</button>
                    </form>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

  </main><!-- End #main -->

  <!-- ======= Footer ======= -->
  <footer id="footer" class="footer">
      <div class="credits">
          Designed by 2022030202033-曾广生</a>
      </div>
  </footer><!-- End Footer -->

  <a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a>

  <!-- Vendor JS Files -->
  <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="assets/vendor/gridjs/dist/gridjs.umd.js"></script>
  <script src="assets/vendor/gridjs/I10n/dist/l10n.umd.js"></script>
  <script src="assets/vendor/moment/moment.js"></script>

  <!-- Template Main JS File -->
  <script src="assets/js/main.js"></script>
  <script>
    // 定义接口地址
  const userInfoUrl = "/api/rest/self"; //用户信息接口
  const userUpdateUrl = "/api/rest/user";
  const passwordUpdateUrl = "/api/rest/self/update-password";
  const avatarUploadUrl = "/api/rest/attachment";
  //定义数据users，存放查询返回的用户数据
  let users = [];
  //表格配置：服务器请求响应处理
  const server = {
      url: userInfoUrl,
      then: (data) => {
          users = data.content;
          return data.content.map((item) => [
              item.id,
              item.username,
              item.enableState,
              item.name,
              item.phone,
              item.email,
              item.updateAt? moment(item.updateAt).format("YYYY-MM-DD hh:mm:ss") : "",
          ]);
      },
      total: (data) => data.totalElements,
  };

  // 页面加载完成后执行
  window.onload = function () {
    let userId;
    // 获取用户信息
    fetch(userInfoUrl)
    .then(response => response.json())
    .then(data => {
      userId = data.id;
      // 更新用户信息
      document.getElementById("userAvatar").src = data.avatar || "assets/img/profile-img.jpg";
      document.getElementById("username").innerText = data.username;
      document.getElementById("department").innerText = data.dept.name;
      document.getElementById("role").innerText = data.role.name;
      document.getElementById("department1").innerText = data.dept.name;
      document.getElementById("role1").innerText = data.role.name;
      document.getElementById("userName").innerText = data.name;
      document.getElementById("userPhone").innerText = data.phone;
      document.getElementById("userEmail").innerText = data.email;
      document.getElementById("name").value = data.name;
      document.getElementById("phone").value = data.phone;
      document.getElementById("email").value = data.email;

      if (data.avatar) {
          document.getElementById('userAvatarImg').src = `/api/rest/attachment/${data.avatar}`;
      } else {
          document.getElementById('userAvatarImg').src = 'assets/img/user.png';
      }
    });

      // 编辑信息表单提交事件
      document.getElementById("editUserForm").addEventListener("submit", function (event) {
          event.preventDefault();
          const updatedInfo = {
              name: document.getElementById("name").value,
              phone: document.getElementById('phone').value,
              email: document.getElementById('email').value
          };
          // 发送更新请求
          fetch(`/api/rest/self`, {
              method: "PATCH",
              headers: {
                  "Content-Type": "application/json"
              },
              body: JSON.stringify(updatedInfo)
          }).then(response => {
              if (response.ok) {
                  alert("信息更新成功！");
                  window.location.reload();
              } else {
                  alert("更新失败，请重试。");
              }
          });
      });
      // 修改密码表单提交事件
      document.getElementById("changePwdForm").addEventListener("submit", function (event) {
          event.preventDefault();
          const oldPassword = document.getElementById("oldPassword").value;
          const newPassword = document.getElementById("newPassword").value;
          const confirmPassword = document.getElementById("confirmPassword").value;

          if (newPassword!== confirmPassword) {
              alert("密码不匹配，请重新输入。");
              return;
          }

          fetch(`/api/rest/self/update-password`, {
              method: "PATCH",
              headers: {
                  "Content-Type": "application/json"
              },
              body: JSON.stringify({ oldPassword: oldPassword,password: newPassword,passwordRepeat: confirmPassword})
          }).then(response => {
              if (response.ok) {
                  alert("密码修改成功！");
                  document.getElementById("changePwdForm").reset();
              } else {
                  alert("修改密码失败，请重试。");
              }
          });
      });

      // 头像上传相关逻辑
      const uploadAvatarButton = document.getElementById('uploadAvatarButton');
      const avatarFileInput = document.getElementById('avatarFileInput');
      const userAvatarImg = document.getElementById('userAvatarImg');
      const uploadAvatarAlert = document.getElementById('uploadAvatarAlert');
      
      //注册“编辑用户表单”中的“删除用头像按钮”的事件监听
      removeAvatarButton.addEventListener("click",(event)=>{
          editUserForm.avatar.value=null;
          userAvatarImg.src="assets/img/user.png";
        });
      //注册“编辑用户表单”中的“上传用头像按钮”的事件监听
      uploadAvatarButton.addEventListener("click", function (event) {
          avatarFileInput.click();
      });

      avatarFileInput.addEventListener("change", function (event) {
          const files = event.target.files;
          if (files.length > 0) {
              const file = files[0];
              const allowedTypes = ["image/jpeg", "image/png"];
              if (!allowedTypes.includes(file.type)) {
                  createAlert(uploadAvatarAlert, "请上传jpg或png格式的图片", "danger");
                  return;
              }
              const maxSize = 1 * 1024 * 1024;
              if (file.size > maxSize) {
                  createAlert(uploadAvatarAlert, "文件太大,请上传小于1M的图片", "danger");
                  return;
              }
              uploadAvatarAlert.innerHTML = "";
              const formData = new FormData();
              formData.append("file", file);
              formData.append("type", "头像");
              //请求附件上传接口
              fetch(avatarUploadUrl, {
                  method: "POST",
                  body: formData
              })
          .then((response) => response.json())
          .then((attachment) => {
                  //附件上传成功后，显示头像
                  userAvatarImg.src = attachment.url;
                  // 这里假设存在一个editUserForm（原代码未完整定义），添加以下语句
                  editUserForm.avatar.value = attachment.id;
              })
          .catch((error) => {
                  createAlert(uploadAvatarAlert, error.message, "danger");
              });
          }
      });
  };
  </script>
</body>

</html>